
package com.example.cia.database.mysql.dao.impl;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.example.cia.database.mysql.dao.IUser;
import com.example.cia.database.pojo.user;
import com.mysql.jdbc.Connection;


public class userImpl extends mysqlDaoImpl implements IUser {
	
	private user User;

	/*
	 * 用户DAO的详细操作
	 */
	
	public userImpl(){
		User = new user();
	}
	
	@Override
	public boolean regist(int id, String password, String address) {
		User.setUser_id(id);
		User.setUser_password(password);
		User.setUser_address(address);
		return add();
	}

	@Override
	public boolean login(int id, String password) throws ClassNotFoundException, SQLException, IOException {
		User.setUser_id(id);
		User.setUser_password(password);
		User.setUser_address("0");
		if(User.getUser_password().equals(queryForOneObject()))
			return true;
		return false;
	}
	
	@Override
	public boolean add(){
		String sql = "INSERT INTO "+getQulifiedTableName()+" VALUES(?,?,?)";
		try {
			databaseManager db = databaseManager.createInstance();
			Connection con = db.getCon();
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, User.getUser_id());
			ps.setString(2,User.getUser_password());
			ps.setString(3, User.getUser_address());
			return (ps.executeUpdate()!=0);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
        return false;		
	}
	
	@Override
	public String queryForOneObject() throws ClassNotFoundException, SQLException, IOException{
		String sql = "SELECT "+getQueryFieldString(1)+" FROM "+
	         getQulifiedTableName()+" WHERE "+getPrimaryKey()+" = ?";
		databaseManager db = databaseManager.createInstance();
		Connection con = db.getCon();
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setInt(1, User.getUser_id());
		ResultSet rs = ps.executeQuery();
		if(rs.next())
			return rs.getString(getQueryFieldString(1));
		else
			return null;
	}
	
	@Override
	public String getTableName(){
		return "user";
	}
	
	/**
	 * @param which 1 获取用户密码 2 获取用户地址
	 */
	@Override
	public String getQueryFieldString(int which){
		switch(which){
		case 1:return "user_password";
		case 2:return "user_address";
		}
		return null;
	}

	@Override
	public String getAddress(int id) throws ClassNotFoundException, SQLException, IOException {
		String sql = "SELECT "+getQueryFieldString(2)+" FROM "+
		         getQulifiedTableName()+" WHERE "+getPrimaryKey()+" = ?";
		databaseManager db = databaseManager.createInstance();
			Connection con = db.getCon();
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			if(rs.next())
				return rs.getString(getQueryFieldString(2));
			else
				return null;
	}
}
